package com.taoye.thread;

public class Demo25 {
	public static void main(String[] args) throws InterruptedException {
		Demo25ServiceChild service = new Demo25ServiceChild();
		Thread t = new Demo25Thread(service);
		t.setName("A");
		t.start();
		Thread t2 = new Demo25Thread(service);
		t2.setName("B");
		t2.start();
		int a = 1;
	}
}

class Demo25Service {
	private int number = 10;
    public synchronized void setNumber(String name) {
		if(name.equals("A")) {
			//线程A先进来设置了以后 线程B立马修改number变量的值测试是否造成脏读
			number = 100;
			System.out.println("线程A设置完成了,当前值为："+number);
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}else {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			number = 200;
			System.out.println("线程B设置完成了,当前值为："+number);
		}
		System.out.println("线程"+name+"的值为：" + number);
	}
}

class Demo25ServiceChild extends Demo25Service {
	
	public void setNumber(String name) {
		System.out.println("子类调用了方法，线程："+Thread.currentThread().getName());
		super.setNumber(name);
	}
}

class Demo25Thread extends Thread {
	private Demo25ServiceChild service;
	
	public Demo25Thread(Demo25ServiceChild service) {
		this.service = service;
	}
	@Override
	public void run() {
		service.setNumber(getName());
	}
}
